package com.bovink.customalbum.album;

import android.animation.ObjectAnimator;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bovink.customalbum.DensityUtils;
import com.bovink.customalbum.R;
import com.jakewharton.rxrelay2.PublishRelay;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.reactivex.functions.Consumer;

import static com.bovink.customalbum.album.AlbumUtils.imageFilter;

/**
 * com.bovink.customalbum.album
 *
 * @author bovink
 * @since 2017/7/1
 */

public class AlbumActivity extends AppCompatActivity {
    private RecyclerView folderImageRv;
    private TextView folderNameTv;
    private GradientDrawableTextView selectedNumTv;
    private LinearLayout albumLl;
    private RecyclerView albumRv;
    private View maskView;

    private FolderImageAdapter folderImageAdapter;

    private List<String> folderPaths = new ArrayList<>();
    private List<ImageFolder> imageFolders = new ArrayList<>();
    private List<String> selectImgList = new ArrayList<>();

    /**
     * 是否已显示相册列表
     */
    private boolean albumIsShowing = false;

    public static PublishRelay<Object> relay;
    /**
     * 已选中图片的数量
     */
    public static int selectedImgNum;

    public static final int SELECT_ALBUM_IMAGE = 10000;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album);

        relay = PublishRelay.create();
        bindViews();

        folderImageRv.setLayoutManager(new GridLayoutManager(this, 3));
        folderImageRv.addItemDecoration(new ImageItemDecoration());
        folderImageAdapter = new FolderImageAdapter(this);
        folderImageRv.setAdapter(folderImageAdapter);

        albumRv.setLayoutManager(new LinearLayoutManager(this));
        AlbumAdapter albumAdapter = new AlbumAdapter(this, imageFolders);
        albumRv.setAdapter(albumAdapter);

        getImages();

        handleEvent();
    }

    @Override
    public void onBackPressed() {
        if (albumIsShowing) {
            albumIsShowing = false;
            showAlbum(false);
        } else {
            setResult(RESULT_CANCELED);
            super.onBackPressed();
        }
    }

    /**
     * 相册列表动画
     *
     * @param show
     */
    private void showAlbum(boolean show) {
        float start = folderImageRv.getMeasuredHeight();
        float end = DensityUtils.dpToPx(this, 50);

        albumRv.setVisibility(View.VISIBLE);
        maskView.setVisibility(View.VISIBLE);
        maskView.setClickable(show);

        // 相册列表动画
        ObjectAnimator translateAnimator = ObjectAnimator.ofFloat(albumRv, "Y", start, end);
        translateAnimator.setDuration(300);

        // 相册遮罩动画
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(maskView, "alpha", 0, 0.7f);
        alphaAnimator.setDuration(300);

        if (show) {
            translateAnimator.start();
            alphaAnimator.start();
        } else {
            translateAnimator.reverse();
            alphaAnimator.reverse();
        }
    }

    private void bindViews() {
        selectedNumTv = (GradientDrawableTextView) findViewById(R.id.tv_selected_num);
        selectedNumTv.setDrawableClickable(false);
        selectedNumTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.putExtra("data", (Serializable) selectImgList);
                setResult(RESULT_OK, intent);
                finish();

            }
        });

        folderImageRv = (RecyclerView) findViewById(R.id.rv_folder_img);
        maskView = findViewById(R.id.view_mask);
        maskView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                albumIsShowing = !albumIsShowing;
                showAlbum(albumIsShowing);
            }
        });

        albumRv = (RecyclerView) findViewById(R.id.rv_album);
        folderNameTv = (TextView) findViewById(R.id.tv_folder_name);
        // 左下角相册
        albumLl = (LinearLayout) findViewById(R.id.ll_album);
        albumLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                albumIsShowing = !albumIsShowing;
                showAlbum(albumIsShowing);

            }
        });

        albumLl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getActionMasked()) {
                    case MotionEvent.ACTION_DOWN:
                        folderNameTv.setTextColor(0xFFC0C0C0);
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        folderNameTv.setTextColor(0xFFFFFFFF);
                        break;
                }
                return false;
            }
        });

        ImageView closeIv = (ImageView) findViewById(R.id.iv_close);
        closeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

    }

    private class ImageItemDecoration extends RecyclerView.ItemDecoration {

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            if (position >= 3) {
                outRect.top = 5;
            }
            if (position % 3 != 0) {
                outRect.left = 5;
            }
        }
    }

    /**
     * 处理事件
     */
    private void handleEvent() {

        relay.subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                // 选择相册事件
                if (o instanceof EventType.SelectAlbumEvent) {
                    EventType.SelectAlbumEvent event = (EventType.SelectAlbumEvent) o;
                    albumIsShowing = !albumIsShowing;
                    showAlbum(albumIsShowing);
                    int position = event.getPosition();
                    handler.sendEmptyMessage(position);

                }

                // 选择图片事件
                if (o instanceof EventType.SelectImageEvent) {
                    EventType.SelectImageEvent event = (EventType.SelectImageEvent) o;

                    // 如果取消选中
                    if (!event.isImgSelected()) {
                        selectImgList.remove(event.getImgPath());
                    }

                    // 如果选中且没添加过
                    if (event.isImgSelected() && !selectImgList.contains(event.getImgPath())) {
                        selectImgList.add(event.getImgPath());
                    }
                    selectedImgNum = selectImgList.size();
                    if (selectedImgNum == 0) {
                        selectedNumTv.setDrawableClickable(false);
                        selectedNumTv.setText("发送");
                    } else {
                        selectedNumTv.setDrawableClickable(true);
                        selectedNumTv.setText("发送(" + selectImgList.size() + "/9)");
                    }
                    System.out.println(event.getImgPath());
                    System.out.println(event.isImgSelected() + "");
                }


            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {


            folderImageAdapter.clearData();
            ImageFolder imageFolder = imageFolders.get(msg.what);
            folderNameTv.setText(imageFolder.getName());
            System.out.println(imageFolder.getPath());
            File imgFolder = new File(imageFolder.getPath());

            List<String> imgList = Arrays.asList(imgFolder.list(imageFilter()));
            folderImageAdapter.setPath(imgFolder.getAbsolutePath() + "/");
            folderImageAdapter.addData(imgList);
            folderImageAdapter.setCheckedImgs(selectImgList);
            folderImageAdapter.notifyDataSetChanged();


        }
    };


    private void getImages() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver contentResolver = getContentResolver();

                Cursor cursor = contentResolver.query(imageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " +
                                MediaStore.Images.Media.MIME_TYPE + "=? or " +
                                MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png", "image/jpg"},
                        MediaStore.Images.Media.DATE_TAKEN + " DESC");//获取图片的cursor，按照时间倒序（发现没卵用)

                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));// 1.获取图片的路径
                    // 存放图片的文件
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;//不获取sd卡根目录下的图片
                    String parentPath = parentFile.getAbsolutePath();//2.获取图片的文件夹信息
                    String parentName = parentFile.getName();
                    ImageFolder imageFolder;//自定义一个model，来保存图片的信息

                    //这个操作，可以提高查询的效率，将查询的每一个图片的文件夹的路径保存到集合中，
                    //如果存在，就直接查询下一个，避免对每一个文件夹进行查询操作
                    if (folderPaths.contains(parentPath)) {
                        continue;
                    } else {
                        folderPaths.add(parentPath);//将父路径添加到集合中
                        imageFolder = new ImageFolder();
                        imageFolder.setLogo(path);
                        imageFolder.setPath(parentPath);
                        imageFolder.setName(parentName);
                    }
                    List<String> pictures = null;
                    try {
                        pictures = Arrays.asList(parentFile.list(imageFilter()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int picSize = pictures.size();//获取每个文件夹下的图片个数
                    if (picSize == 0) {
                        continue;
                    }
                    imageFolder.setCount(picSize);//传入每个相册的图片个数
                    imageFolders.add(imageFolder);//添加每一个相册
                }
                cursor.close();
                handler.sendEmptyMessage(0);
            }
        }).start();
    }
}
